<?php

/**
 * 最终打印解决方案
 * 提供多种打印方法的完整实现
 */

include 'vendor/autoload.php';

use Smalot\Cups\Builder\Builder;
use Smalot\Cups\Manager\JobManager;
use Smalot\Cups\Manager\PrinterManager;
use Smalot\Cups\Model\Job;
use Smalot\Cups\Transport\Client;
use Smalot\Cups\Transport\ResponseParser;
use Smalot\Cups\Transport\ImprovedClient;

class FinalPrintSolution {
    private $printerIP;
    private $printerPort;
    private $username;
    private $password;
    
    public function __construct($printerIP = '10.1.0.12', $printerPort = 631, $username = null, $password = null) {
        $this->printerIP = $printerIP;
        $this->printerPort = $printerPort;
        $this->username = $username;
        $this->password = $password;
    }
    
    /**
     * 主要打印方法 - 按照用户提供的格式
     */
    public function printWithStandardFormat($filePath, $jobName = 'Standard Print Job', $copies = 1) {
        echo "=== 标准格式打印测试 ===\n";
        echo "时间: " . date('Y-m-d H:i:s') . "\n";
        echo "文件: {$filePath}\n";
        echo "打印机: {$this->printerIP}:{$this->printerPort}\n\n";
        
        try {
            // 按照用户提供的格式初始化组件
            $client = new Client($this->username, $this->password, [
                'remote_socket' => "tcp://{$this->printerIP}:{$this->printerPort}",
                'timeout' => 30
            ]);
            $builder = new Builder();
            $responseParser = new ResponseParser();
            
            echo "✅ 组件初始化成功\n";
            
            // 创建打印机管理器
            $printerManager = new PrinterManager($builder, $client, $responseParser);
            echo "✅ 打印机管理器创建成功\n";
            // 查找打印机
            $printerUri = "ipp://{$this->printerIP}:{$this->printerPort}/ipp/print";
            echo "🔍 正在查找打印机: {$printerUri}\n";
            
            $printer = $printerManager->findByUri($printerUri);
            var_dump($printer);
            echo "✅ 打印机查找成功\n";
            
            // 创建作业管理器
            $jobManager = new JobManager($builder, $client, $responseParser);
            echo "✅ 作业管理器创建成功\n";
            
            // 创建打印作业
            $job = new Job();
            $job->setName($jobName);
            $job->setUsername($this->username ?: 'admin');
            $job->setCopies($copies);
            $job->setPageRanges('1');
            $job->addFile($filePath);
            $job->addAttribute('media', 'A4');
            $job->addAttribute('fit-to-page', true);
            
            echo "📄 作业配置完成\n";
            
            // 发送打印作业
            echo "🖨️  正在发送打印作业...\n";
            $result = $jobManager->send($printer, $job);
            
            echo "✅ 标准格式打印成功!\n";
            echo "作业结果: " . print_r($result, true) . "\n";
            
            return true;
            
        } catch (Exception $e) {
            echo "❌ 标准格式打印失败: " . $e->getMessage() . "\n";
            echo "正在尝试备用方法...\n\n";
            
            // return $this->printWithAlternativeMethods($filePath, $jobName, $copies);
        }
    }
    
    /**
     * 备用打印方法
     */
    private function printWithAlternativeMethods($filePath, $jobName, $copies) {
        $success = false;
        
        // 方法1: Windows系统打印
        echo "🖥️  尝试方法1: Windows系统打印\n";
        $success = $this->printWithWindows($filePath);
        
        // 方法2: 网络打印机共享
        if (!$success) {
            echo "\n🔗 尝试方法2: 网络打印机共享\n";
            $success = $this->printWithNetworkShare($filePath);
        }
        
        return $success;
    }
    
    /**
     * Windows系统打印
     */
    private function printWithWindows($filePath) {
        try {
            // 方法1: 使用print命令
            $commands = [
                "print {$filePath}",
                "notepad /p {$filePath}"
            ];
            
            foreach ($commands as $command) {
                echo "执行: {$command}\n";
                $output = shell_exec($command . ' 2>&1');
                
                if (strpos($output, 'Unable to initialize') === false && 
                    strpos($output, 'error') === false) {
                    echo "✅ Windows系统打印成功!\n";
                    return true;
                }
            }
            
            echo "❌ Windows系统打印失败\n";
            return false;
            
        } catch (Exception $e) {
            echo "❌ Windows打印异常: " . $e->getMessage() . "\n";
            return false;
        }
    }
    
    /**
     * 网络打印机共享打印
     */
    private function printWithNetworkShare($filePath) {
        try {
            // 尝试通过网络共享访问打印机
            $shareCommands = [
                "copy {$filePath} \\\\{$this->printerIP}\\print",
                "net use \\\\{$this->printerIP}\\ipp && copy {$filePath} \\\\{$this->printerIP}\\ipp"
            ];
            
            foreach ($shareCommands as $command) {
                echo "执行: {$command}\n";
                $output = shell_exec($command . ' 2>&1');
                
                if (strpos($output, '1 file(s) copied') !== false) {
                    echo "✅ 网络共享打印成功!\n";
                    return true;
                }
            }
            
            echo "❌ 网络共享打印失败\n";
            return false;
            
        } catch (Exception $e) {
            echo "❌ 网络共享打印异常: " . $e->getMessage() . "\n";
            return false;
        }
    }
    
    /**
     * 创建测试文件
     */
    public function createTestFile($filename = 'test_print.txt') {
        $content = "打印测试文件\n";
        $content .= "===================\n";
        $content .= "时间: " . date('Y-m-d H:i:s') . "\n";
        $content .= "打印机: {$this->printerIP}:{$this->printerPort}\n";
        $content .= "测试内容: 这是一个IPP打印测试\n";
        $content .= "编码: UTF-8\n";
        $content .= "页面: 1/1\n";
        $content .= "===================\n";
        
        file_put_contents($filename, $content);
        return $filename;
    }
}

// 使用示例
echo "=== 最终打印解决方案 ===\n\n";

// 创建打印解决方案实例
$printSolution = new FinalPrintSolution('10.1.0.12', 631);

// 创建测试文件
$testFile = $printSolution->createTestFile();
echo "✅ 测试文件创建成功: {$testFile}\n\n";

// 按照用户提供的格式进行打印
$success = $printSolution->printWithStandardFormat(
    $testFile,
    '最终测试打印作业',
    1
);

if ($success) {
    echo "\n🎉 打印任务完成!\n";
} else {
    echo "\n😞 所有打印方法都失败了\n";
    echo "\n💡 建议:\n";
    echo "1. 检查打印机是否支持IPP协议\n";
    echo "2. 确认打印机网络设置\n";
    echo "3. 尝试手动添加网络打印机\n";
    echo "4. 联系打印机厂商获取驱动程序\n";
}

echo "\n=== 程序结束 ===\n";